<template>
  <div style="position: relative;">
    <div id="container" style="z-index: 100"></div>
    <!-- 查询区域 -->
    <div class="edit-wrap">
      <div class="table-page-search-wrapper">
        <j-select-area placeholder="请选择区域id" v-model="areaId" :selectType="2" />
        <a-button type="primary" @click="setPipManageScore" style="margin: 0 10px">设置管点处理范围</a-button>
        <a-button type="danger" @click="switchShowWushuiLine" style="margin: 0 10px">污水管</a-button>
        <a-button type="primary" @click="switchShowYushuiLine" style="margin: 0 10px">雨水管</a-button>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { getPipPoint, editPipPoint, getpipLine } from '@/api/pipPoint'

import { wgs84togcj02 } from '@/utils/coordtransform'

let equipMarks = [] // 设报警备marker(icon为动图)-背景
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      map: null,
      warnsbxx: null,
      areaId: '',
      pipData: null,
      editFlag: false,
      showWushuiPip: true,
      showYushuiPip: true,
      yvshuiPipLineMarkerList: [],
      wvshuiPipLineMarkerList: [],
      lines: {}
    }
  },
  watch: {
    areaId: {
      handler: function(areaId) {
        if (areaId) {
          this.getPipPoint(areaId)
          this.handleGetPipLine()
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    // 获取雨水污水管数据
    async handleGetPipLine() {
      const areaId = this.areaId
      const [res, res1] = await Promise.all([getpipLine(1, areaId), getpipLine(2, areaId)])
      const yvshuiPipLineList = res.result || []
      const wushuiPipLineList = res1.result || []
      // console.log("获取雨水污水管数据", yvshuiPipLineList, wushuiPipLineList);
      this.yvshuiPipLineMarkerList = yvshuiPipLineList.map(line => {
        return {
          path: line.map(point => wgs84togcj02(point.longitude, point.latitude)),
          pipPointNos: [line[0].pipPointNo, line[line.length - 1].pipPointNo]
        }
      })
      this.wvshuiPipLineMarkerList = wushuiPipLineList.map(line => {
        return {
          path: line.map(point => wgs84togcj02(point.longitude, point.latitude)),
          pipPointNos: [line[0].pipPointNo, line[line.length - 1].pipPointNo]
        }
      })
      if (this.showWushuiPip) {
        this.levelChange(true, 2, '污水管', '#F74020')
      }
      if (this.showYushuiPip) {
        this.levelChange(true, 1, '雨水管', '#00D3FF')
      }
    },
    switchShowWushuiLine() {
      this.showWushuiPip = !this.showWushuiPip
      this.levelChange(this.showWushuiPip, 2, '污水管', '#F74020')
    },
    switchShowYushuiLine() {
      this.showYushuiPip = !this.showYushuiPip
      this.levelChange(this.showYushuiPip, 1, '雨水管', '#00D3FF')
    },
    levelChange(flag, type, lineName, color) {
      if (flag) {
        const makerList = type === 1 ? this.yvshuiPipLineMarkerList : this.wvshuiPipLineMarkerList
        this.addmanyPolyline(makerList, lineName, color)
      } else {
        this.removeLine(lineName)
      }
    },
    addmanyPolyline(makerList, lineName, color) {
      if (makerList.length == 0) return
      AMapUI.load(['ui/misc/PathSimplifier'], PathSimplifier => {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！')
          return
        }
        //创建组件实例
        this.lines[lineName] = new PathSimplifier({
          zIndex: 100,
          map: this.map, //所属的地图实例
          getPath: function(pathData) {
            return pathData.path
          },
          getHoverTitle: function() {
            return ''
          },
          renderOptions: {
            //线的样式
            pathLineStyle: {
              strokeStyle: color,
              lineWidth: 2,
              borderStyle: color,
              borderWidth: 0,
              dirArrowStyle: true
            },
            pathLineHoverStyle: {
              strokeStyle: color,
              lineWidth: 4,
              borderStyle: color,
              borderWidth: 0,
              dirArrowStyle: true
            },
            startPointStyle: {
              radius: 0,
              fillStyle: '#109618',
              strokeStyle: '#109618',
              lineWidth: 0
            },
            endPointStyle: {
              radius: 0,
              fillStyle: '#109618',
              strokeStyle: '#109618',
              lineWidth: 0
            },
            keyPointStyle: {
              radius: 0,
              fillStyle: '#109618',
              strokeStyle: '#109618',
              lineWidth: 0
            }
          },
          clickToSelectPath: false
        })
        //构建轨迹
        this.lines[lineName].setData(makerList)
        // // 管道点击显示管道信息弹窗
        // this.lines[lineName].on('pathClick', (e, { pathData }) => {
        //   // console.log(pathData.pipPointNos)
        //   this.$parent.getLineInfo(pathData.pipPointNos[0], pathData.pipPointNos[1], [
        //     e.originalEvent.lnglat.lng,
        //     e.originalEvent.lnglat.lat
        //   ])
        // })
      })
      // this.$parent.map.setFitView(path);
    },
    removeLine(lineName) {
      if (this.lines[lineName] && this.lines[lineName].setData) {
        this.lines[lineName].setData([])
        this.lines[lineName] = null
      }
    },
    async getPipPoint(areaId) {
      const res = await getPipPoint(0, areaId, 0)
      if (res && res.result) {
        this.initPipMark(res.result)
      } else {
        this.$$message.warning('改区域暂无设备')
      }
    },
    setPipManageScore() {
      this.editFlag = true
      if (this.polygonEditor) {
        this.polygonEditor.on('end', event => {
          //获取 结束后触发
          if (this.editFlag) {
            const pathobjArr = event.target.getPath()
            const path = pathobjArr.map(item => [item.lng, item.lat])
            editPipPoint({
              ...this.pipData,
              manageScope: JSON.stringify(path)
            })
            equipMarks = []
            // 编辑成功重新获取数据
            this.getPipPoint(this.areaId)
          }
        })
        this.polygonEditor.close()
      }
    },
    initPipMark(pipList) {
      this.removePipMarkers()
      // 过滤无设备管点
      const repeatPipPointPipNos = []
      const pipPointList = pipList
        .filter(obj => obj.equNo && obj.equNo.length != 0)
        .map(item => {
          // 判断管点是否安装多个设备
          if (repeatPipPointPipNos.includes(item.pipNo)) {
            item.showOtherEquip = true
          } else {
            item.showOtherEquip = false
          }
          // 处理管点经纬度 84to2000
          var curPosition = wgs84togcj02(item.longitude, item.latitude)
          item.lnglat = [...curPosition]
          // 判断显示管点icon的路径
          let iconUrl = ''
          let icon = ''
          icon = this.parsePipPonitMarkerIconUrl(item)
          item.labelMarkerIcon = icon
          iconUrl = require(`@/assets/amap/${icon}`)
          let marker = new AMap.Marker({
            position: curPosition,
            extData: {
              item
            },
            cursor: 'pointer',
            icon: new AMap.Icon({
              image: iconUrl,
              size: [40, 40], //图标大小
              imageSize: [40, 40]
            }),
            offset: new AMap.Pixel(-20, -40),
            zIndex: 100
          })
          marker.on('click', e => {
            this.markerClick(e.target.getExtData().item)
            // this.$emit('markerClick', e.target.getExtData().item, e.lnglat)
          })
          // 向全局equipMarks添加报警标记
          equipMarks.push(marker)
          return item
        })
      this.initLabelsLayerSbxx()
    },
    removePipMarkers() {
      if (equipMarks.length) {
        this.map.remove(equipMarks)
        equipMarks = []
        this.warnsbxx = null
      }
    },
    async initLabelsLayerSbxx() {
      if (this.warnsbxx) return
      let layerName = 'warnsbxx'
      // console.log(layerName)
      this[layerName] = new AMap.LabelsLayer({
        zooms: [3, 23],
        zIndex: 100,
        collision: false
      })
      // 将图层添加到地图
      this.map.add(this[layerName])
      this.map.add(equipMarks)
      this.map.setFitView(equipMarks)
    },
    removeEquipMarkers() {
      if (equipMarks.length) {
        this.map.remove(equipMarks)
        equipMarks = []
      }
    },
    markerClick(pipData) {
      console.log('pipData', pipData)
      this.pipData = { ...pipData }
      let longitude = pipData.lnglat[0]
      let latitude = pipData.lnglat[1]
      const initNum = 0.001
      let path = []
      if (pipData.manageScope) {
        path = JSON.parse(pipData.manageScope)
      } else {
        path = [
          [longitude, latitude],
          [longitude, latitude + initNum],
          [longitude - initNum, latitude + initNum],
          [longitude - initNum, latitude]
        ]
      }

      if (this.polygon && this.polygonEditor) {
        this.editFlag = false
        this.polygonEditor.close()
        this.map.remove([this.polygon])
      }
      this.polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#FF33FF',
        strokeWeight: 2,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: '#1791fc',
        zIndex: 50,
        bubble: true
      })
      this.map.add([this.polygon])
      this.map.plugin(['AMap.PolygonEditor'], () => {
        // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
        this.polygonEditor = new AMap.PolygonEditor(this.map, this.polygon)
        // 开启编辑模式
        this.polygonEditor.open()
      })
    },
    // 处理marker展示icon
    parsePipPonitMarkerIconUrl(item) {
      let icon = ''
      let showOtherEquip = item.showOtherEquip
      // 有设备显示
      const status = item.onlintStatus || item.equOnlineStatus
      switch (status) {
        case 2:
          icon = item.showOtherEquip ? 'icon-equips-normal.png' : 'icon-equip-normal.png'
          break
        case 3:
          icon = item.showOtherEquip ? 'icon-equips-abnormal.png' : 'icon-equip-abnormal.png'
          break
        case 4:
          icon = item.showOtherEquip ? 'icon-equips-abnormal.png' : 'icon-equip-abnormal.png'
          break
        default:
          icon = item.showOtherEquip ? 'icon-equips-abnormal.png' : 'icon-equip-abnormal.png'
          break
      }
      return icon
    },
    // 初始化地图
    initMap() {
      var _this = this
      AMapLoader.load({
        key: '7bf1afe0a111e75bc96b5f5d0553b5f3', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['MapType'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          // 是否加载 AMapUI，缺省不加载
          version: '1.1', // AMapUI 缺省 1.1
          plugins: ['misc/PathSimplifier'] // 需要加载的 AMapUI ui插件
        }
      })
        .then(AMap => {
          _this.map = new AMap.Map('container', {
            //设置地图容器id
            // resizeEnable: true,
            viewMode: '3D', //是否为3D地图模式
            zoom: 16, //设置地图的缩放级别
            center: [119.646354, 29.129608], //初始化地图中心点位置
            mapStyle: 'amap://styles/3efe3caae4d86d89083fd8e4e911a826' //'amap://styles/macaron' // 设置地图的显示样式
          })
          // 在地图创建之后使用Map对象的setMapStyle方法来修改自定义地图
          // this.map.setMapStyle('amap://styles/whitesmoke');
          // _this.initMarks()
          // _this.initMark()
        })
        .catch(e => {
          console.log(e)
        })
    },
    /**
     * 普通点坐标
     */
    initMark() {
      var icon = new AMap.Icon({
        size: new AMap.Size(40, 40),
        image: 'https://i.postimg.cc/3rDqPJvb/1.png',
        imageSize: new AMap.Size(40, 40)
      })
      // var markerList = [marker1,marker2]
      var marker1 = new AMap.Marker({
        position: new AMap.LngLat(119.645354, 29.135608),
        title: '师范大学',
        icon: icon,
        offset: new AMap.Pixel(-20, -40)
      })
      var marker2 = new AMap.Marker({
        position: new AMap.LngLat(119.644354, 29.135708),
        title: '师范大学2',
        icon: icon,
        offset: new AMap.Pixel(-20, -40)
      })
      var marker3 = new AMap.Marker({
        position: new AMap.LngLat(119.642554, 29.135708),
        title: '师范大学3',
        icon: icon,
        offset: new AMap.Pixel(-20, -40)
      })
      this.map.add([marker1, marker2, marker3])
    },
    /**
     * 海量点坐标
     */
    initMarks() {
      let mass
      let style = [
        {
          url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b1.png',
          anchor: new AMap.Pixel(14, 15), //图标显示位置偏移量
          size: new AMap.Size(26, 30), //图标的尺寸
          zIndex: 5 //点展示优先级，默认为使用样式的索引值
        },
        {
          url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b1.png',
          anchor: new AMap.Pixel(14, 15),
          size: new AMap.Size(20, 30),
          zIndex: 4
        },
        {
          url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b1.png',
          anchor: new AMap.Pixel(18, 20),
          size: new AMap.Size(36, 36),
          zIndex: 3
        },
        {
          url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b1.png',
          anchor: new AMap.Pixel(18, 20),
          size: new AMap.Size(36, 36),
          zIndex: 2
        },
        {
          url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b1.png',
          anchor: new AMap.Pixel(18, 20),
          size: new AMap.Size(36, 36)
        },
        {
          url: 'https://a.amap.com/jsapi_demos/static/images/mass2.png',
          anchor: new AMap.Pixel(18, 20),
          size: new AMap.Size(36, 36),
          zIndex: 0
        }
      ]
      let data = [
        {
          lnglat: ['116.466752,39.951042'],
          name: 'one',
          id: 1
        },
        {
          lnglat: ['116.675933,39.986343'],
          name: 'two',
          id: 2
        },
        {
          lnglat: ['117.270073,37.96162'],
          name: 'three',
          id: 3
        },
        {
          lnglat: ['117.212164,31.831641'],
          name: 'fthoor',
          id: 4
        }
      ]
      mass = new AMap.MassMarks(data, {
        opacity: 0.8,
        zIndex: 2,
        cursor: 'pointer',
        style: style
      })
      console.log(mass)
      console.log(this.map)
      mass.setMap(this.map)
    }
  }
}
</script>
<style scoped>
#container {
  position: absolute;
  top: 0;
  left: 0;
  width: 1420px;
  height: 1158px;
}

.edit-wrap {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100;
}
.table-page-search-wrapper {
  display: flex;
}
</style>
